import { createSlice } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'
import type { RootState, AppThunk } from '@/store'

type CounterStateType = {
  value: number
  status: 'idle' | 'loading' | 'succeeded' | 'faild'
}

type LoadingStatus = CounterStateType['status']

const initialState: CounterStateType = {
  value: 0,
  // idle, loading, succeeded, faild
  status: 'idle'
}

const counterSlice = createSlice({
  //  name, initialState, reducers
  // name 是当前切片的唯一标识符
  name: 'counter',
  // initialState 是初始数据
  initialState,
  // reducers 用来描述如何变更当前切片中的数据
  reducers: {
    // 自增
    increment(state, action: PayloadAction<number | undefined>) {
      console.log(action)
      state.value += action.payload || 1
    },
    // 自减
    decrement(state, action: PayloadAction<number | undefined>) {
      state.value -= action.payload || 1
    },
    setLoadingStatus(state, action: PayloadAction<LoadingStatus>) {
      state.status = action.payload
    }
  }
})

export default counterSlice.reducer

// selectors
export const selectCount = (state: RootState) => state.count.value
export const selectLoading = (state: RootState) => state.count.status === 'loading'

// action creators
// 用来创建并返回 action 对象的函数，叫做 action creator
export const { increment, decrement, setLoadingStatus } = counterSlice.actions

// thunk action creators
export const incrementAsync = (step?: number): AppThunk => {
  // 注意，这里 return 的函数，就是 thunk action
  return (dispatch) => {
    // 执行异步操作
    setTimeout(() => {
      dispatch(increment(step))
    }, 1000)
  }
}

export const decrementAsync = (step?: number): AppThunk => {
  return (dispatch) => {
    // 执行异步操作
    // 在执行异步操作之前，把状态设置 loading
    dispatch(setLoadingStatus('loading'))
    setTimeout(() => {
      dispatch(decrement(step))
      // 在异步操作成功之后，把状态设置为 succeeded
      dispatch(setLoadingStatus('succeeded'))
    }, 1000)
  }
}
